﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Text.RegularExpressions;
using HtmlAgilityPack;

namespace Windvoice.Library
{
    public class HtmlHelper
    {
        public static string FixHtml(string htmlString)
        {
            if (string.IsNullOrEmpty(htmlString)) return string.Empty;

            var hdoc = new HtmlDocument() { OptionWriteEmptyNodes = true };
            hdoc.LoadHtml(htmlString);
            return hdoc.DocumentNode.WriteTo();
        }

        public static string HtmlSummary(string content, int length)
        {
            //如果输入字符串长度小于截取长度，直接返回
            if (content.Length <= length) return content;
            //如果输入字符串竟未包含html代码，那就直接截取
            if (!content.Contains("<")) return content.Substring(0, length);
            //如果输入字符串中包含手动截取标记，则返回标记前的内容
            if (content.Contains("<!-- summary end -->")) return Regex.Split(content, "<!-- summary end -->")[0];

            var IsTag = false; //当前字符是否在标签中
            var Summary = String.Empty; //截取的子字符串
            var TagName = String.Empty; //当前标签名称
            var TagArray = new { Left = new ArrayList(), Right = new ArrayList() }; //左标签数组、右标签数组

            content = FixHtml(content);

            foreach (var current in content)
            {
                if (length <= 0) break; //在截取长度>0的情况下，循环遍历html字符

                if (current == '<') //当前字符为<，进入html标签
                {
                    IsTag = true;
                }
                else if (current == '>') //当前字符为>，移出html标签
                {
                    //如果当前标签名称以/开头，则此标签为闭合标签，应加入右标签数组
                    if (TagName.Trim().StartsWith("/"))
                        TagArray.Right.Add(TagName);
                    //否则应加入左标签数组，但应考虑自闭合标签不加入闭合标签数组
                    else if (!TagName.Trim().EndsWith("/") && !"img|br|input".Split('|').Contains(TagName.ToLower()))
                        TagArray.Left.Add(TagName.Trim().ToLower().Split(' ')[0]);

                    IsTag = false; //标记已移出html标签
                    TagName = String.Empty; //完成标签加入标签数组后，应重置此变量
                }
                else
                {
                    if (IsTag) //如果在html标签中，则拼积当前标签名称
                        TagName += current;
                    else //否则为纯文本内容，计数器开始自减，直到减为0，循环退出
                        length--;
                }

                Summary += current; //拼积截取的子字符串
            }

            Summary = Summary.Trim();

            //从左标签数组中移除已闭合的标签
            //TagArray.Left.RemoveRange(0, TagArray.Right.Count);
            while (TagArray.Right.Count > 0)
            {
                TagArray.Left.RemoveAt(TagArray.Left.IndexOf(TagArray.Right[0].ToString().Replace("/", "")));
                TagArray.Right.RemoveAt(0);
            }

            //剩余标签未闭合，逆序以html闭合标签格式拼接至截取的子字符串末尾
            if (TagArray.Left.Count > 0)
                for (var i = TagArray.Left.Count - 1; i >= 0; i--)
                {
                    Summary += String.Format("</{0}>", TagArray.Left[i].ToString());
                }

            return Summary;
        }
    }
}
